using System;
using System.Data.Linq.Mapping;
using System.Linq;

namespace TruyenTranhCrawler.Data
{
    [Table]
    public class BookType : BaseObject
    {
        #region Properties
        [Column(IsPrimaryKey = true)]
        public int TypeId { get; set; }
        [Column]
        public string BookIds { get; set; }
        #endregion

        #region Methods
        public static void AddBook(int typeId, int bookId)
        {
            using (var context = new CmsDataContext())
            {
                var bookids = context.BookTypes.Where(x => x.TypeId == typeId).Select(x => x.BookIds).FirstOrDefault();
                if (bookids != null)
                {
                    var full = "," + bookids + ",";
                    if (full.IndexOf("," + bookId + ",") < 0)
                    {
                        bookids += "," + bookId;
                        context.ExecuteCommand("update BookType set BookIds={0} where TypeId={1}", bookids, typeId);
                    }
                }
                else
                {
                    context.ExecuteCommand("insert into BookType(TypeId,BookIds) values({0},{1})", typeId, bookId);
                }
            }
        }
        public static void RemoveBook(int typeId, int bookId)
        {
            using (var context = new CmsDataContext())
            {
                var bookids = context.BookTypes.Where(x => x.TypeId == typeId).Select(x => x.BookIds).FirstOrDefault();
                if (bookids != null)
                {
                    var bids =
                        bookids.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(n => Convert.ToInt32(n))
                            .ToList();
                    if (bids.Contains(bookId))
                    {
                        bids.Remove(bookId);
                        bookids = string.Join(",", bids);   //new values
                        context.ExecuteCommand("update BookType set BookIds={0} where TypeId={1}", bookids, typeId);
                    }
                }
            }
        }
        #endregion Methods
    }
}
